import { createRouter, createWebHistory } from 'vue-router';
import Login from '../views/auth/Login.vue';
import Register from '../views/auth/Register.vue';
import NotFound from '../views/error/NotFound.vue';
import ServerError from '../views/error/ServerError.vue';
import Error from '../views/error/Error.vue';
import MainLayout from '../layout/MainLayout.vue';
import Dashboard from '../views/dashboard/index.vue';
import UserProfile from '../views/user/profile.vue';
import UserList from '../views/user/list.vue';
import store from '../store';
import { ElMessage } from 'element-plus';
import { validateToken } from '@/api/auth';

const routes = [
  {
    path: '/',
    component: Login,
    meta: {
      requiresAuth: false,
      redirectIfAuth: true
    }
  },
  {
    path: '/register',
    name: 'Register',
    component: Register,
    meta: {
      requiresAuth: false,
      redirectIfAuth: true
    }
  },
  {
    path: '/admin',
    component: MainLayout,
    redirect: '/dashboard',
    meta: {
      requiresAuth: true
    },
    children: [
      {
        path: '/dashboard',
        name: 'Dashboard',
        component: Dashboard,
        meta: {
          title: '首页',
          icon: 'HomeFilled',
          requiresAuth: true
        }
      },
      {
        path: '/user/profile',
        name: 'UserProfile',
        component: UserProfile,
        meta: {
          title: '个人中心',
          requiresAuth: true
        }
      },
      {
        path: '/user/list',
        name: 'UserList',
        component: UserList,
        meta: {
          title: '用户管理',
          icon: 'User',
          requiresAuth: true
        }
      },
      {
        path: '/application/request',
        name: 'ApplicationRequest',
        component: () => import('../views/application/request.vue'),
        meta: {
          title: '入党申请书',
          icon: 'Document',
          requiresAuth: true
        }
      },
      {
        path: '/application/volunteer',
        name: 'ApplicationVolunteer',
        component: () => import('../views/application/volunteer.vue'),
        meta: {
          title: '入党志愿书',
          icon: 'Document',
          requiresAuth: true
        }
      },
      {
        path: '/conversation/list',
        name: 'ConversationList',
        component: () => import('../views/conversation/list.vue'),
        meta: {
          title: '谈话记录管理',
          icon: 'ChatDotRound',
          requiresAuth: true
        }
      },
      {
        path: '/training/list',
        name: 'TrainingList',
        component: () => import('../views/training/list.vue'),
        meta: {
          title: '培养信息管理',
          icon: 'Collection',
          requiresAuth: true
        }
      },
      {
        path: '/assessment/list',
        name: 'AssessmentList',
        component: () => import('../views/assessment/list.vue'),
        meta: {
          title: '考察信息管理',
          icon: 'Aim',
          requiresAuth: true
        }
      },
      {
        path: '/background-check/list',
        name: 'BackgroundCheckList',
        component: () => import('../views/background-check/list.vue'),
        meta: {
          title: '政审信息管理',
          icon: 'Check',
          requiresAuth: true
        }
      },
      {
        path: '/training-management/list',
        name: 'TrainingManagementList',
        component: () => import('../views/training-management/list.vue'),
        meta: {
          title: '培训管理',
          icon: 'School',
          requiresAuth: true
        }
      },
      {
        path: '/branch-meeting/list',
        name: 'BranchMeetingList',
        component: () => import('../views/branch-meeting/list.vue'),
        meta: {
          title: '支部大会信息管理',
          icon: 'Connection',
          requiresAuth: true
        }
      },
      {
        path: '/system',
        name: 'System',
        meta: {
          title: '系统设置',
          icon: 'Setting',
          requiresAuth: true,
          roles: ['管理员'] // 只有管理员可以访问
        },
        redirect: '/dashboard'  // 临时重定向到首页，因为暂时没有系统设置页面
      }
    ]
  },
  // 错误页面路由
  {
    path: '/404',
    name: 'NotFound',
    component: NotFound,
    meta: {
      title: '页面不存在'
    }
  },
  {
    path: '/500',
    name: 'ServerError',
    component: ServerError,
    meta: {
      title: '服务器错误'
    }
  },
  {
    path: '/error/:code',
    name: 'Error',
    component: Error,
    props: true,
    meta: {
      title: '错误'
    }
  },
  // 捕获所有未匹配的路由，重定向到404
  {
    path: '/:pathMatch(.*)*',
    redirect: '/404'
  }
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

router.beforeEach(async (to, from, next) => {
  // 更新页面标题
  document.title = to.meta.title || '党员发展管理系统';

  const token = localStorage.getItem('token');
  const userRole = localStorage.getItem('userRole');

  // 如果路由需要认证
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!token) {
      ElMessage.warning('请先登录');
      next('/');
      return;
    }

    // 验证token是否有效
    try {
      const response = await validateToken(token);
      if (response.data.code === 200) {
        // 如果用户信息不存在，获取用户信息
        if (!store.getters.currentUser) {
          await store.dispatch('fetchUserInfo');
        }

        // 检查角色权限
        if (userRole === '用户') {
          ElMessage.error('您没有权限访问管理系统');
          store.dispatch('logout');
          next('/');
          return;
        }

        // 检查路由是否有角色限制
        if (to.meta.roles && !to.meta.roles.includes(userRole)) {
          ElMessage.error('您没有权限访问该页面');
          next('/dashboard');
          return;
        }

        next();
      } else {
        ElMessage.error(response.data.msg || '登录已过期，请重新登录');
        store.dispatch('logout');
        next('/');
        return;
      }
    } catch (error) {
      console.error('Token验证失败:', error);
      ElMessage.error('验证失败，请重新登录');
      store.dispatch('logout');
      next('/');
    }
  }
  // 如果用户已登录且要访问登录/注册页，重定向到仪表盘
  else if (to.matched.some(record => record.meta.redirectIfAuth) && token) {
    // 检查角色权限，如果是普通用户则登出并提示
    if (userRole === '用户') {
      ElMessage.error('您没有权限访问管理系统');
      store.dispatch('logout');
      next('/');
      return;
    }
    next('/dashboard');
  }
  else {
    next();
  }
});

export default router;